package com.ccl.iot.privates;

import java.util.ArrayList;

public class QueueInvokeBuffer<TYPE> {
	public interface InvokeDelegate<TYPE>{
		public void onInvoke(TYPE aObject);
		public void lastTask(TYPE aObject);
	}
	
	/*
	 * 	Non-static functions
	 */
	private QueueInvoke iInvoker = null;
	private InvokeDelegate<TYPE> iDelegate = null;
	
	private ArrayList<TYPE> iBuffer = null;
	
	private boolean isRunningQueue  = false;
	
	public QueueInvokeBuffer(String aName, int aDelay, InvokeDelegate<TYPE> aDelegate){
		iDelegate = aDelegate;
		
		if (iDelegate != null){
			iInvoker = new QueueInvoke(aName, aDelay, new QueueInvoke.InvokeListener() {
				@Override
				public void onInvoke() {
					if(iBuffer != null){
						TYPE tItem = null;
						
						synchronized(iInvoker){
							if (iBuffer != null){
								if (iBuffer.size() > 0){
									tItem = iBuffer.get(0);

									iBuffer.remove(0);
								}
							}
						}
						
						if (tItem != null){
							iDelegate.onInvoke(tItem);
							if(iBuffer.size() == 0){
								iDelegate.lastTask(tItem);
							}
						}else{
							iInvoker.cancel();
							isRunningQueue = false;
						}
					}
				}
			});
			
		}
	}
	
	public void put(TYPE aObject) {
		if (aObject != null){
			synchronized(iInvoker){
				if (iBuffer == null){
					iBuffer = new ArrayList<TYPE>();
				}
				
				if (iBuffer.contains(aObject) == false){
					iBuffer.add(aObject);
				}
				
				if(!isRunningQueue){
					isRunningQueue = true;
					iInvoker.invoke();
				}
			}
		}
	}
	
	public void clear(){
		synchronized(iInvoker){
			iInvoker.cancel();
			
			if (iBuffer != null && iBuffer.size() > 0){
				iBuffer.clear();
			}
		}
	}
}
